<template>
    <div class="userContainer">
        <div class="header">
            <div>
                <el-button type="primary" @click="isAdd = true">添加管理员</el-button>
                <el-button type="danger" :disabled="!selectedCount" style="margin: 0.6rem" @click="multiDelete">
                    批量删除
                </el-button>
            </div>
            <span>共有数据：{{ userDataLength }} 条</span>
        </div>
        <div class="search"></div>
        <el-table
            :data="userData"
            style="width: 100%"
            empty-text="没有数据"
            ref="form"
            @selection-change="handleSelectionChange"
            v-loading="isLoading"
            row-key="userID"
            @row-click="detailHandler"
        >
            <el-table-column type="selection" width="55" :reserve-selection="true" />
            <el-table-column prop="userID" label="用户ID" width="80"></el-table-column>
            <el-table-column prop="username" label="用户名" width="120"></el-table-column>
            <el-table-column prop="password" label="密码" width="120"></el-table-column>
            <el-table-column prop="sex" label="性别" width="80"></el-table-column>
            <el-table-column prop="telephone" label="手机号码" width="140"></el-table-column>
            <el-table-column prop="email" label="邮箱" width="140"></el-table-column>
            <el-table-column prop="createDate" label="创建时间" width="160"></el-table-column>
            <el-table-column prop="userState" label="用户状态" width="80">
                <template #default="scope">
                    <el-tag v-if="scope.row.userState">可用</el-tag>
                    <el-tag v-else type="info">拉黑</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="isAdmin" label="是否管理员" width="100">
                <template #default="scope">
                    <el-tag v-if="scope.row.isAdmin">是</el-tag>
                    <el-tag v-else type="info">否</el-tag>
                </template>
            </el-table-column>

            <el-table-column width="200" label="操作" fixed="right">
                <template #default="scope">
                    <el-button type="primary" @click.stop="resetPassword(scope.row)">重置密码</el-button>
                    <el-button
                        type="danger"
                        plain
                        @click.stop="banHandler(scope.row)"
                        v-if="scope.row.userState"
                        :disabled="scope.row.username === username"
                        >拉黑
                    </el-button>
                    <el-button v-else plain @click.stop="recoverHandler(scope.row)">恢复</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="footer">
            <el-pagination
                background
                :page-sizes="[5, 10, 15, 20]"
                layout="sizes, prev, pager, next"
                :page-count="pageCount"
                :default-page-size="pageSize"
                :current-page="currentPage"
                @size-change="pageSizeChange"
                @current-change="currentChangeHandler"
            />
            <span>当前选中：{{ selectedCount }} 行</span>
        </div>
        <el-dialog v-model="isDetail" title="用户详情" class="detail">
            <!-- {{ selectedRow }} -->
            <div>用户ID：{{ selectedRow.userID }}</div>
            <div>用户名：{{ selectedRow.username }}</div>
            <div>密码：{{ selectedRow.password }}</div>
            <div>性别：{{ selectedRow.sex }}</div>
            <div>手机号码：{{ selectedRow.telephone }}</div>
            <div>邮箱：{{ selectedRow.email }}</div>
            <div>创建时间：{{ selectedRow.createDate }}</div>
            <div>
                用户状态：
                <span v-if="selectedRow.userState === 1">可用</span>
                <span style="color: red" v-else>拉黑</span>
            </div>
            <div>
                是否管理员：
                <span style="color: red" v-if="selectedRow.isAdmin === 1">是</span>
                <span v-else>否</span>
            </div>
        </el-dialog>
        <el-drawer v-model="isAdd">
            <AddAdmin @close="handleClose" />
        </el-drawer>
    </div>
</template>

<script>
import { Search } from "@element-plus/icons-vue";
import service from "@/utils/request";
import { ElMessage, ElMessageBox } from "element-plus";
import { userStore } from "@/store/user";
import AddAdmin from "../../components/AddAdmin.vue";
export default {
    components: {
        Search,
        AddAdmin,
    },
    data() {
        return {
            userData: [],
            userDataLength: 0,
            pageSize: 5,
            currentPage: 1,
            pageCount: 0,
            isLoading: true,
            selectedRows: [],
            selectedCount: 0,
            selectedId: [],
            isDetail: false,
            selectedRow: {},
            isAdd: false,
            username: "",
        };
    },
    beforeMount() {
        this.refresh();
    },
    methods: {
        handleClose() {
            this.isAdd = false;
            this.refresh();
        },
        // 详细信息
        detailHandler(row, column, event) {
            this.selectedRow = row;
            this.isDetail = true;
        },
        async refresh() {
            this.isLoading = true;
            this.searchUsername = "";
            await service.get(`/user/page?pageNum=${this.currentPage}&pageSize=${this.pageSize}`).then((res) => {
                // console.log(res.data);
                this.pageCount = res.data.data.pages;
                this.userData = res.data.data.records;
                this.userDataLength = res.data.data.total;
            });
            this.username = JSON.parse(sessionStorage.getItem("userInfo")).username;
            // console.log(this.username);
            this.isLoading = false;
        },
        // 多选操作
        handleSelectionChange(rows) {
            // console.log(rows);
            this.selectedRows = rows;
            this.selectedCount = this.selectedRows.length;
            let id = [];
            rows.forEach((item) => id.push(item.userID));
            this.selectedId = id;
            // console.log(this.selectedId);
        },
        // 批量删除
        multiDelete() {
            ElMessageBox.confirm(`确认要删除用户ID：${this.selectedId} 吗？`, "警告", {
                type: "warning",
                confirmButtonText: "确认",
                cancelButtonText: "取消",
            }).then(() => {
                this.selectedId.forEach((item) => {
                    service({
                        method: "delete",
                        url: `/user/delete?id=${item}`,
                        headers: {
                            token: userStore().token,
                        },
                    })
                        .then(() => {
                            ElMessage({
                                type: "success",
                                message: "删除成功",
                            });
                        })
                        .catch((err) => {
                            ElMessage({
                                type: "error",
                                message: "删除失败",
                            });
                            console.log(err);
                        });
                    this.refresh();
                });
            });
        },
        // 对用户进行重置密码操作
        resetPassword(row) {
            ElMessageBox.confirm(`确定要重置 ${row.username} 的密码为111吗`, "警告", {
                confirmButtonText: "确认",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    service({
                        method: "get",
                        url: `/user/resetPassword?id=${row.userID}`,
                    }).then((res) => {
                        ElMessage({
                            type: "info",
                            message: "密码重置成功",
                        });
                        this.refresh();
                    });
                })
                .catch(() => {});
        },
        // 单页数据个数切换
        pageSizeChange(e) {
            this.pageSize = e;
            this.refresh();
        },
        // 页码切换
        currentChangeHandler(e) {
            this.currentPage = e;
            // console.log(e);
            this.refresh();
            service.get(`/user/page?pageNum=${this.currentPage}&pageSize=${this.pageSize}`).then((res) => {});
        },
        // 恢复拉黑
        recoverHandler(row) {
            service({
                method: "post",
                url: "/user/saveUser",
                headers: {
                    token: userStore().token,
                    "Content-type": "application/json",
                },
                data: {
                    ...row,
                    password: "111",
                    userState: 1,
                },
            }).then((res) => {
                ElMessage({
                    type: "success",
                    message: "取消拉黑成功，密码已重置为111",
                });
                this.refresh();
            });
        },
        // 拉黑
        banHandler(row) {
            service({
                method: "post",
                url: "/user/saveUser",
                headers: {
                    token: userStore().token,
                    "Content-type": "application/json",
                },
                data: {
                    ...row,
                    userState: 0,
                },
            }).then((res) => {
                ElMessage({
                    type: "success",
                    message: "拉黑成功",
                });
                this.refresh();
            });
        },
    },
};
</script>

<style lang="scss" scoped>
.userContainer {
    display: flex;
    flex-direction: column;

    .header {
        display: flex;
        flex-direction: row;
        margin-bottom: 1rem;
        justify-content: space-between;
        align-items: center;
    }

    .footer {
        margin-top: 1rem;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
    }

    .detail {
        line-height: 2rem;
    }
}
</style>
